import java.util.LinkedList;
import java.util.List;

import DLX.DLXResult;
import DLX.DLXResultProcessor;
import DLX.DLXSudokuSolver;

public class DancingLinksSolver implements SudokuAlgorithm {

    @Override
    public List<List<Integer>> solve(List<List<Integer>> puzzle) {

        final DLXSudokuSolver solver = new DLXSudokuSolver();
        solver.solve(convertToByte(puzzle), new DLXResultProcessor() {
            @Override
            public boolean processResult(DLXResult result) {
                solver.decodeDLXResult(result);
                return false;
            }
        });

        return convertToInteger(solver.getDLXResult());

    }

    public byte[] convertToByte(List<List<Integer>> puzzle) {
        byte[] newpuzzle = new byte[81];
        int indexcount = 0;
        for (int i = 0; i < 9; i++) {
            for (int j = 0; j < 9; j++) {
                newpuzzle[indexcount] = puzzle.get(i).get(j).byteValue();
                indexcount++;
            }
        }
        return newpuzzle;
    }

    public List<List<Integer>> convertToInteger(byte[] puzzle) {
        List<List<Integer>> solvedPuzzle = new LinkedList<List<Integer>>();
        int indexcount = 0;
        for (int i = 0; i < 9; i++) {
            LinkedList<Integer> col = new LinkedList<Integer>();
            solvedPuzzle.add(col);
            for (int j = 0; j < 9; j++) {
                col.add(new Integer(puzzle[indexcount]));
                indexcount++;
            }
        }

        return solvedPuzzle;
    }
}
